import 'dart:async';
import 'dart:convert';

import 'package:card_swiper/card_swiper.dart';
import 'package:city_pickers/city_pickers.dart';
import 'package:eplorex/models/message/partial_text.dart';
import 'package:eplorex/pages/my/module/user_avatar_module.dart';
import 'package:eplorex/providers/user_context.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';

import '../../../dao/follow_dao.dart';
import '../../../dao/momentinfo_dao.dart';
import '../../../models/follow/userprofile_model.dart';
import '../../../models/moment/moment_model.dart';
import '../../../utils/HttpUtil.dart';
import 'comment_area_widget.dart';

class MomentInfoDetailsPage extends StatefulWidget {
  int? momentId;

  MomentInfoDetailsPage(this.momentId);

  @override
  State<MomentInfoDetailsPage> createState() => _MomentInfoDetailsPageState();
}

class _MomentInfoDetailsPageState extends State<MomentInfoDetailsPage> {
  late Future<MomentModel?> _momentModel;
  late TextEditingController _textController;

  final _commentController = TextEditingController();
  final FocusNode _focusNode = FocusNode();
  var _showSendBtn = false;
  var _commentText="";

  @override
  void initState() {
    super.initState();
    _momentModel = MomentInfoDao.fetch(widget.momentId);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      extendBodyBehindAppBar: true,
      extendBody: true,
      appBar: AppBar(
        backgroundColor: Colors.transparent,
        elevation: 0,
        title: Container(
          child: FutureBuilder(
              future: _momentModel,
              builder: (BuildContext context, AsyncSnapshot snapshot) {
                if (snapshot.connectionState == ConnectionState.waiting ||
                    snapshot.data == null) {
                  return Container(
                    child: Text(""),
                  );
                }
                final MomentModel momentData = snapshot.data!;
                return Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    UserAvatarModule(
                        profileModel: UserProfileModel.fromJson({
                      'userId': momentData.creatorInfo.userId,
                      'userName': momentData.creatorInfo.userName,
                      'avatar': momentData.creatorInfo.avatar
                    })),
                    if (momentData.creatorInfo.userId != UserContext.cxt()!.uid)
                      FilledButton(
                        onPressed: () {
                          FollowDao.followUser(
                              momentData.creatorInfo.userId, true);
                        },
                        child: Text("关注"),
                        style: FilledButton.styleFrom(
                            foregroundColor: Colors.white,
                            backgroundColor: Colors.blue,
                            minimumSize: Size(60, 30),
                            padding: EdgeInsets.zero),
                      )
                  ],
                );
              }),
        ),
        actions: [IconButton(onPressed: () {}, icon: Icon(Icons.share))],
      ),
      body: FutureBuilder(
        future: _momentModel,
        builder: (BuildContext context, AsyncSnapshot snapshot) {
          if (snapshot.connectionState == ConnectionState.waiting ||
              snapshot.data == null) {
            return Container(
              child: Text("load...."),
            );
          }
          final MomentModel momentData = snapshot.data!;
          Result result = CityPickers.utils()
              .getAreaResultByCode(momentData.userPosition ?? '110000');
          return ListView(
            children: [
              _getSwiper(momentData.multiMedia),
              Container(
                color: Colors.white,
                margin: EdgeInsets.symmetric(horizontal: 5),
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.start,
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Padding(
                      padding: EdgeInsets.all(5),
                      child: Text(
                        momentData.title,
                        style: TextStyle(
                            fontWeight: FontWeight.bold, fontSize: 16),
                      ),
                    ),
                    Padding(
                      padding: EdgeInsets.all(5),
                      child: Text(
                        momentData.content,
                        style: TextStyle(fontSize: 18),
                      ),
                    ),
                    Container(
                      margin: EdgeInsets.all(5),
                      child: Row(
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        children: [
                          Wrap(
                            children: [
                              Text('${result.provinceName} ' ?? "未知   "),
                              Text(momentData.publishTime ?? "1月前")
                            ],
                          ),
                          Container(
                            child: Wrap(
                              children: [
                                GestureDetector(
                                  onTap: () {
                                    _showCommentInput(widget.momentId!.toInt(),
                                        widget.momentId!.toInt());
                                  },
                                  child: const Padding(
                                    padding: EdgeInsets.only(right: 10),
                                    child: Icon(
                                      Icons.comment_outlined,
                                      size: 18,
                                      color: Colors.grey,
                                    ),
                                  ),
                                ),
                                GestureDetector(
                                  onTap: () {
                                    print("like");
                                  },
                                  child: const Padding(
                                    padding: EdgeInsets.only(right: 5),
                                    child: Icon(
                                      Icons.favorite_border,
                                      size: 18,
                                      color: Colors.grey,
                                    ),
                                  ),
                                ),
                              ],
                            ),
                          )
                        ],
                      ),
                    )
                  ],
                ),
              ),
              CommentAreaWidget(
                commentInput: _showCommentInput,
                commentsCnt: momentData.commentsCnt,
                momentId: widget.momentId,
              )
            ],
          );
        },
      ),
      bottomNavigationBar: _buildBottomNavigationBar(),
    );
  }

  void _handleSendPressed(PartialText text) {}

  Widget? _buildBottomNavigationBar() {
    return SafeArea(
      // bottom: false,
      child: Container(
          height: 80,
          color: Colors.white,
          padding: const EdgeInsets.only(left: 10, right: 10),
          child: Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            mainAxisSize: MainAxisSize.min,
            children: [
              CircleAvatar(
                radius: 15,
                backgroundImage: NetworkImage(UserContext.cxt()?.avatar ?? ""),
              ),
              const SizedBox(
                width: 15,
              ),
              Expanded(
                child: Container(
                    margin: EdgeInsets.only(top: 15, bottom: 15),
                    alignment: Alignment.center,
                    decoration: BoxDecoration(
                        color: Colors.grey[200],
                        borderRadius: BorderRadius.circular(10.0)),
                    child: TextField(
                      readOnly: true,
                      decoration: const InputDecoration(
                          // contentPadding: EdgeInsets.only(left: 10, right: 10),
                          border: InputBorder.none,
                          hintText: '文明评论'),
                      onTap: (){
                        _showCommentInput(widget.momentId!.toInt(),
                            widget.momentId!.toInt());
                        },
                    )),
              )
            ],
          )),
    );
  }

  Widget _getSwiper(List<MultiMedia> multiMedias) {
    // var height = MediaQuery.of(context).size.width / 350.0 * 250.0;
    return SizedBox(
      height: MediaQuery.of(context).size.height * 0.5,
      child: Swiper(
        itemBuilder: (BuildContext context, int index) {
          return Image.network(
            multiMedias[index].url,
            fit: BoxFit.cover,
          );
        },
        autoplay: true,
        itemCount: multiMedias.length,
        pagination: SwiperPagination(),
        // control: SwiperControl(),
      ),
    );
  }

  void _showCommentInput(num parentId, num replayId) {
    _clearCommentContext();
    showModalBottomSheet(
      context: context,
      isScrollControlled: true,
      // backgroundColor: Colors.transparent,
      builder: (BuildContext context) {
        return StatefulBuilder(builder: (context, setDialogState) {
          return AnimatedPadding(
            padding: MediaQuery.of(context).viewInsets, // 我们可以根据这个获取需要的padding
            duration: Duration(milliseconds: 10),
            child: Container(
              height: 100,
              padding: const EdgeInsets.only(top: 10, left: 10, right: 10),
              decoration: const BoxDecoration(
                color: Colors.white70,
                borderRadius: BorderRadius.only(
                  topLeft: Radius.circular(20),
                  topRight: Radius.circular(20),
                ),
              ),
              child: Column(
                children: [
                  Row(
                    children: [
                      Expanded(
                          flex: 2,
                          child: IconButton(
                              onPressed: () {},
                              icon: Icon(Icons.keyboard_voice_rounded))),
                      Expanded(
                        flex: 12,
                        child: TextField(
                          autofocus: true,
                          controller: _commentController,
                          focusNode: _focusNode,
                          decoration: const InputDecoration(
                            contentPadding: EdgeInsets.symmetric(horizontal: 8),
                            fillColor: Colors.white,
                            filled: true,
                            border:
                                OutlineInputBorder(borderSide: BorderSide.none),
                            hintText: '输入评论',
                          ),
                          keyboardType: TextInputType.text,
                          textInputAction: TextInputAction.send,
                          onChanged: (str) {
                            if (str != null && str.isNotEmpty) {
                              _showSendBtn = true;
                              _commentText=str;
                            } else {
                              _showSendBtn = false;
                            }
                            setDialogState(() {});
                          },
                        ),
                      ),
                      Expanded(
                          flex: 2,
                          child: IconButton(
                              onPressed: () {},
                              icon: Icon(Icons.emoji_emotions_outlined))),
                      Expanded(
                          flex: 2,
                          child: IconButton(
                              onPressed: () {},
                              icon: Icon(Icons.add_circle_outline))),
                      if (_showSendBtn)
                        Expanded(
                            flex: 3,
                            child: FilledButton(
                                onPressed: () {

                                  _comment(_commentText, parentId, replayId);
                                  Navigator.of(context).pop();
                                },
                                child: Text("发送"),
                                style: FilledButton.styleFrom(
                                    foregroundColor: Colors.white,
                                    backgroundColor: Colors.blue,
                                    minimumSize: Size(60, 30),
                                    padding: EdgeInsets.zero))),
                    ],
                  ),
                  SizedBox(height: 16),
                ],
              ),
            ),
          );
        });
      },
    );
  }

  void _comment(String? commentContent, num parentId, num replyId) async {
    var response = await HttpUtil.getInstance().post("/api/comment/v1/reply",
        data: jsonEncode({
          'creatorId': UserContext.cxt()!.uid,
          'momentId': widget.momentId,
          'commentId': parentId,
          'replyId': replyId,
          'comment': commentContent
        }));

    if (response!.statusCode == 200) {
      print("评论成功");
    } else {
      print("s");
    }
  }

  void _clearCommentContext() {
    _commentController.clear();
    _showSendBtn = false;
    _commentText="";
  }
}
